package com.gongpingjialoan.utility;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.gongpingjialoan.api.API;
import com.gongpingjialoan.constant.Const;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

/**
 * 表单上传图片
 * 
 * 
 */
public class HttpSubmitImage extends Thread
{
    /** url */
    private String url = "";
    
    /** 图片路径 */
    private String material;
    
    private Handler handler;
    
    private Context mContext;

    String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成
    String PREFIX = "--", LINE_END = "\r\n";
    String CONTENT_TYPE = "multipart/form-data"; // 内容类型
    private static final int TIME_OUT = 20 * 1000; // 超时时间
    private static final String CHARSET = "utf-8"; // 设置编码
    
    /** 单例对象 */
    private static HttpSubmitImage httpSubmitForm = null;
    
    /**
     * 单例构造.
     */
    public static HttpSubmitImage getInstance()
    {
        if (httpSubmitForm == null)
        {
            httpSubmitForm = new HttpSubmitImage();
        }
        return httpSubmitForm;
    }
    
    private HttpSubmitImage()
    {
    }
    

    public HttpSubmitImage(Context context, Handler handler, String url, String filepath)
    {
        this.mContext = context;
        this.handler = handler;
        this.url = url;
        this.material = filepath;
    }
    


    @Override
    public void run()
    {
        int messWhat = Const.UPLOAD_FAIL;

        Object obj = null;

        try {
            URL url = new URL(API.uploadPic);
            HttpURLConnection conn = null;
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(TIME_OUT);
            conn.setConnectTimeout(TIME_OUT);
            conn.setDoInput(true); // 允许输入流
            conn.setDoOutput(true); // 允许输出流
            conn.setUseCaches(false); // 不允许使用缓存
            conn.setRequestMethod("POST"); // 请求方式
            conn.setRequestProperty("Charset", CHARSET); // 设置编码
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary="
                    + BOUNDARY);
            File file = new File(material);

            if (file != null) {
                /**
                 * 当文件不为空，把文件包装并且上传
                 */
                OutputStream outputSteam = conn.getOutputStream();

                DataOutputStream dos = new DataOutputStream(outputSteam);
                StringBuffer sb = new StringBuffer();
                sb.append(PREFIX);
                sb.append(BOUNDARY);
                sb.append(LINE_END);
                /**
                 * 这里重点注意： name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
                 * filename是文件的名字，包含后缀名的 比如:abc.png
                 */

                sb.append("Content-Disposition: form-data; name=\"image\"; filename=\""
                        + file.getName() + "\"" + LINE_END);
                sb.append("Content-Type: application/octet-stream; charset="
                        + CHARSET + LINE_END);
                sb.append(LINE_END);
                dos.write(sb.toString().getBytes());
                InputStream is = new FileInputStream(file);
                byte[] bytes = new byte[1024];
                int len = 0;
                while ((len = is.read(bytes)) != -1) {
                    dos.write(bytes, 0, len);
                }
                is.close();
                dos.write(LINE_END.getBytes());
                byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END)
                        .getBytes();
                dos.write(end_data);
                dos.flush();
                /**
                 * 获取响应码 200=成功 当响应成功，获取响应的流
                 */
                int res = conn.getResponseCode();
                if (res == 200) {
                    InputStream result = conn.getInputStream();
                    String str = inputStreamToString(result).toString();
                    JSONObject json = new JSONObject(str);
                    if (NetUtil.isSuccess(json)){
                        messWhat = Const.UPLOAD_SUCCESS;
                        obj = json.get("url");
                    }else{
                        messWhat = Const.UPLOAD_FAIL;
                    }
                }else{
//                    String meeage = inputStreamToString(conn.getErrorStream()).toString();
                    messWhat = Const.UPLOAD_FAIL;
                }
            }
        } catch (Exception e) {

            messWhat = Const.UPLOAD_FAIL;
        }


        handler.obtainMessage(messWhat);
        Message message = new Message();
        message.what = messWhat;
        message.obj = obj;
        handler.sendMessage(message);
    }

    // Fast Implementation
    private StringBuilder inputStreamToString(InputStream is) throws IOException {
        String line = "";
        StringBuilder total = new StringBuilder();

        // Wrap a BufferedReader around the InputStream
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));

        // Read response until the end
        while ((line = rd.readLine()) != null) {
            total.append(line);
        }

        // Return full string
        return total;
    }


    /**
     * 删除过期的文件
     * 
     * @param dir
     * @return
     */
    public long deleteExpireFile(File dir)
    {
        long size = 0;
        if (dir.exists())
        {
            File[] list = dir.listFiles();
            if (list != null && list.length > 0)
            {
                long now = new Date().getTime();
                for (File file : list)
                {
                    if (file.isFile())
                    {
                        
                        long mtime = file.lastModified();
                        
                        // 超过10分钟删除
                        if ((now - mtime) > 60000)
                        {
                            if (file.delete())
                                size++;
                        }
                    }
                }
            }
        }
        return size;
    }
    
    public String zoomBitmap(Context context, String path, int wh[])
    {
        File dir = new File(FileUtil.getStorageDirectory(), "upload");
        dir.mkdirs();
        
        deleteExpireFile(dir);
        
        String temppath = new File(dir, System.currentTimeMillis() + ".jpg").getAbsolutePath();
        Options bitmapFactoryOptions = new BitmapFactory.Options();
        // 下面这个设置是将图片边界不可调节变为可调节
        bitmapFactoryOptions.inJustDecodeBounds = true;
        
        bitmapFactoryOptions.inSampleSize = 2;
        int outWidth = bitmapFactoryOptions.outWidth;
        int outHeight = bitmapFactoryOptions.outHeight;
        
        float imagew = 640f;
        float imageh = 720f;
        int yRatio = (int)Math.ceil(outHeight / imageh);
        int xRatio = (int)Math.ceil(outWidth / imagew);
        if (yRatio > 1 || xRatio > 1)
        {
            if (yRatio > xRatio)
            {
                bitmapFactoryOptions.inSampleSize = yRatio;
            }
            else
            {
                bitmapFactoryOptions.inSampleSize = xRatio;
            }
        }
        bitmapFactoryOptions.inJustDecodeBounds = false;
        
        // WeakReference<Bitmap> bm = new WeakReference<Bitmap>(BitmapFactory.decodeFile(path, bitmapFactoryOptions));
        
        Log.d("", "path=" + path);
        
        Bitmap bm = BitmapFactory.decodeFile(path, bitmapFactoryOptions);
        wh[0] = bm.getWidth();
        wh[1] = bm.getHeight();
        File file = new File(temppath);
        if (bm == null)
            return "";
        try
        {
            file.createNewFile();
            OutputStream outStream = new FileOutputStream(file);
            // bm.get().compress(android.graphics.Bitmap.CompressFormat.JPEG, 100, outStream);
            
            compressImage(bm, outStream);
            
            outStream.flush();
            outStream.close();
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        
        if (bm != null && !bm.isRecycled())
        {
            bm.recycle();
            bm = null;
            
        }
        System.gc();
        return temppath;
    }
    
    private void compressImage(Bitmap image, OutputStream outStream)
    {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 300)
        { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();// 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;// 每次都减少10
        }
        baos.reset();
        image.compress(Bitmap.CompressFormat.JPEG, options, outStream);
        
        //
        // ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//
        // 把压缩后的数据baos存放到ByteArrayInputStream中
        //
        // // 把ByteArrayInputStream数据生成图片
        // return new SoftReference<Bitmap>(BitmapFactory.decodeStream(isBm, null, null)).get();
    }
}
